package com.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.patrol.auth.dao.AdminUserDao;
import com.patrol.auth.pojo.AdminUser;
import com.patrol.service.UserImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author 宋灿
 * @version 1.0
 * @description: TODO
 * @date 2021/8/13 18:40
 */
@Slf4j
@Transactional
@Service
public class UserImageServiceImpl implements UserImageService {
    @Resource
    private AdminUserDao adminUserDao;

    /**
     * 头像上传
     *
     * @param
     * @return
     */
    @Override
    public boolean headerImageUpload(AdminUser adminUser, String staticPath) {
        log.info("数据库更新");
        String url = adminUser.getImg();
        //使用findByUrl（）方法，判断userCheck是否为空（在数据库中是否存在）
        AdminUser userCheck = adminUserDao.findByUrl(url);
        if (userCheck == null) {
            QueryWrapper<AdminUser> qw = new QueryWrapper<>();
            qw.eq("username", adminUser.getUsername());
            AdminUser user = adminUserDao.selectOne(qw);
            if (null != user.getImg()) {
                String oldImg = user.getImg();
                File file = new File(staticPath + "/" + oldImg);
                file.delete();
            }
            //不存在，执行插入url操作
            boolean b = adminUserDao.updatePhotoUrl(adminUser.getUsername(), adminUser.getImg()) != 0;
            return b;
        } else {
            return false;
        }
    }
}
